import os
from typing import Optional
from jinja2 import Environment, FileSystemLoader
from app.db.models import Resume
from sqlalchemy.orm import Session
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib import colors
from datetime import datetime
import tempfile

# 配置Jinja2模板环境
templates_dir = os.path.join(os.path.dirname(__file__), "..", "templates")
jinja_env = Environment(loader=FileSystemLoader(templates_dir))

# 确保模板目录存在
def ensure_templates_dir():
    if not os.path.exists(templates_dir):
        os.makedirs(templates_dir)
        # 创建默认模板文件
        create_default_templates()

# 创建默认模板文件
def create_default_templates():
    # 创建默认模板
    default_template = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ resume.title }}</title>
    <style>
        body {
            font-family: 'SimHei', 'Arial', sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        h1, h2, h3 {
            color: #2c3e50;
            margin-top: 0;
        }
        h1 {
            font-size: 24px;
            border-bottom: 2px solid #3498db;
            padding-bottom: 5px;
        }
        h2 {
            font-size: 18px;
            margin-top: 20px;
            border-left: 4px solid #3498db;
            padding-left: 10px;
        }
        .personal-info {
            margin-bottom: 20px;
        }
        .section {
            margin-bottom: 20px;
        }
        .item {
            margin-bottom: 15px;
        }
        .item-header {
            font-weight: bold;
            display: flex;
            justify-content: space-between;
        }
        .skills {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        .skill-tag {
            background-color: #ecf0f1;
            padding: 3px 10px;
            border-radius: 15px;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <h1>{{ resume.personal_info.full_name }}</h1>
    
    <div class="personal-info">
        {% if resume.personal_info.email %}Email: {{ resume.personal_info.email }} | {% endif %}
        {% if resume.personal_info.phone %}Phone: {{ resume.personal_info.phone }} | {% endif %}
        {% if resume.personal_info.address %}Address: {{ resume.personal_info.address }}{% endif %}
    </div>
    
    {% if resume.personal_info.summary %}
    <div class="section">
        <h2>个人总结</h2>
        <p>{{ resume.personal_info.summary }}</p>
    </div>
    {% endif %}
    
    {% if resume.education %}
    <div class="section">
        <h2>教育经历</h2>
        {% for edu in resume.education %}
        <div class="item">
            <div class="item-header">
                <span>{{ edu.institution }}</span>
                <span>{{ edu.start_date }} - {{ edu.end_date }}</span>
            </div>
            <div>{{ edu.degree }}, {{ edu.major }}</div>
            {% if edu.description %}
            <p>{{ edu.description }}</p>
            {% endif %}
        </div>
        {% endfor %}
    </div>
    {% endif %}
    
    {% if resume.work_experience %}
    <div class="section">
        <h2>工作/实习经历</h2>
        {% for exp in resume.work_experience %}
        <div class="item">
            <div class="item-header">
                <span>{{ exp.position }} at {{ exp.company }}</span>
                <span>{{ exp.start_date }} - {{ exp.end_date }}</span>
            </div>
            {% if exp.description %}
            <p>{{ exp.description }}</p>
            {% endif %}
            {% if exp.achievements %}
            <p><strong>成就：</strong>{{ exp.achievements }}</p>
            {% endif %}
        </div>
        {% endfor %}
    </div>
    {% endif %}
    
    {% if resume.skills %}
    <div class="section">
        <h2>技能</h2>
        <div class="skills">
            {% for skill in resume.skills %}
            <span class="skill-tag">{{ skill.name }} ({{ skill.level }}/5)</span>
            {% endfor %}
        </div>
    </div>
    {% endif %}
    
    {% if resume.certificates %}
    <div class="section">
        <h2>证书</h2>
        {% for cert in resume.certificates %}
        <div class="item">
            <div class="item-header">
                <span>{{ cert.name }}</span>
                <span>{{ cert.issue_date }}</span>
            </div>
            {% if cert.issuing_authority %}
            <div>颁发机构：{{ cert.issuing_authority }}</div>
            {% endif %}
        </div>
        {% endfor %}
    </div>
    {% endif %}
</body>
</html>
    """
    
    # 产品岗模板
    product_template = default_template.replace('border-left: 4px solid #3498db;', 'border-left: 4px solid #e74c3c;')
    
    # 金融岗模板
    finance_template = default_template.replace('border-left: 4px solid #3498db;', 'border-left: 4px solid #2ecc71;')
    
    # 教育岗模板
    education_template = default_template.replace('border-left: 4px solid #3498db;', 'border-left: 4px solid #9b59b6;')
    
    # 写入模板文件
    with open(os.path.join(templates_dir, "default.html"), "w", encoding="utf-8") as f:
        f.write(default_template)
    with open(os.path.join(templates_dir, "product.html"), "w", encoding="utf-8") as f:
        f.write(product_template)
    with open(os.path.join(templates_dir, "finance.html"), "w", encoding="utf-8") as f:
        f.write(finance_template)
    with open(os.path.join(templates_dir, "education.html"), "w", encoding="utf-8") as f:
        f.write(education_template)

# 生成PDF格式的简历
def generate_resume_pdf(resume: Resume, db: Session, template_type: str = "default") -> Optional[str]:
    """
    生成PDF格式的简历
    
    Args:
        resume: 简历对象
        db: 数据库会话
        template_type: 模板类型
        
    Returns:
        生成的PDF文件路径
    """
    try:
        # 确保数据库会话中有完整的关联数据
        db.refresh(resume)
        db.refresh(resume.personal_info) if resume.personal_info else None
        for edu in resume.education: db.refresh(edu)
        for exp in resume.work_experience: db.refresh(exp)
        for skill in resume.skills: db.refresh(skill)
        for cert in resume.certificates: db.refresh(cert)
        
        # 创建临时文件
        fd, file_path = tempfile.mkstemp(suffix=".pdf")
        os.close(fd)
        
        # 创建PDF文档
        doc = SimpleDocTemplate(file_path, pagesize=letter)
        elements = []
        styles = getSampleStyleSheet()
        
        # 添加自定义样式
        styles.add(ParagraphStyle(name='Heading1', fontSize=22, bold=True, spaceAfter=12, textColor=colors.darkblue))
        styles.add(ParagraphStyle(name='Heading2', fontSize=16, bold=True, spaceAfter=6, textColor=colors.navy))
        styles.add(ParagraphStyle(name='Heading3', fontSize=14, bold=True, spaceAfter=3))
        styles.add(ParagraphStyle(name='Normal', fontSize=12, leading=16))
        styles.add(ParagraphStyle(name='Contact', fontSize=12, leading=14))
        
        # 添加个人信息
        if resume.personal_info:
            elements.append(Paragraph(resume.personal_info.full_name, styles['Heading1']))
            
            contact_info = []
            if resume.personal_info.email: contact_info.append(resume.personal_info.email)
            if resume.personal_info.phone: contact_info.append(resume.personal_info.phone)
            if resume.personal_info.address: contact_info.append(resume.personal_info.address)
            
            if contact_info:
                elements.append(Paragraph(" | ".join(contact_info), styles['Contact']))
                elements.append(Spacer(1, 12))
            
            # 添加个人总结
            if resume.personal_info.summary:
                elements.append(Paragraph("个人总结", styles['Heading2']))
                elements.append(Paragraph(resume.personal_info.summary, styles['Normal']))
                elements.append(Spacer(1, 12))
        
        # 添加教育经历
        if resume.education:
            elements.append(Paragraph("教育经历", styles['Heading2']))
            for edu in resume.education:
                elements.append(Paragraph(f"{edu.degree}，{edu.major}，{edu.institution}", styles['Heading3']))
                elements.append(Paragraph(f"{edu.start_date} - {edu.end_date}", styles['Normal']))
                if edu.description:
                    elements.append(Paragraph(edu.description, styles['Normal']))
                elements.append(Spacer(1, 6))
            elements.append(Spacer(1, 12))
        
        # 添加工作经历
        if resume.work_experience:
            elements.append(Paragraph("工作/实习经历", styles['Heading2']))
            for exp in resume.work_experience:
                elements.append(Paragraph(f"{exp.position}，{exp.company}", styles['Heading3']))
                elements.append(Paragraph(f"{exp.start_date} - {exp.end_date}", styles['Normal']))
                if exp.description:
                    elements.append(Paragraph(exp.description, styles['Normal']))
                if exp.achievements:
                    elements.append(Paragraph(f"成就：{exp.achievements}", styles['Normal']))
                elements.append(Spacer(1, 6))
            elements.append(Spacer(1, 12))
        
        # 添加技能
        if resume.skills:
            elements.append(Paragraph("技能", styles['Heading2']))
            skill_data = []
            for skill in resume.skills:
                skill_data.append([f"{skill.name}", f"熟练程度：{skill.level}/5"])
            
            if skill_data:
                # 创建表格样式
                table_style = TableStyle([
                    ('FONTNAME', (0, 0), (-1, -1), 'SimHei'),
                    ('FONTSIZE', (0, 0), (-1, -1), 12),
                    ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                    ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                    ('INNERGRID', (0, 0), (-1, -1), 0.5, colors.grey),
                    ('BOX', (0, 0), (-1, -1), 0.5, colors.grey)
                ])
                
                # 创建表格
                skill_table = Table(skill_data, colWidths=[200, 150])
                skill_table.setStyle(table_style)
                elements.append(skill_table)
                elements.append(Spacer(1, 12))
        
        # 添加证书
        if resume.certificates:
            elements.append(Paragraph("证书", styles['Heading2']))
            for cert in resume.certificates:
                elements.append(Paragraph(cert.name, styles['Heading3']))
                elements.append(Paragraph(f"颁发日期：{cert.issue_date}", styles['Normal']))
                if cert.issuing_authority:
                    elements.append(Paragraph(f"颁发机构：{cert.issuing_authority}", styles['Normal']))
                elements.append(Spacer(1, 6))
        
        # 构建PDF
        doc.build(elements)
        
        return file_path
        
    except Exception as e:
        print(f"生成PDF简历失败: {str(e)}")
        # 清理临时文件
        if 'file_path' in locals() and os.path.exists(file_path):
            try:
                os.remove(file_path)
            except:
                pass
        return None

# 生成DOCX格式的简历
def generate_resume_docx(resume: Resume, db: Session, template_type: str = "default") -> Optional[str]:
    """
    生成DOCX格式的简历
    
    Args:
        resume: 简历对象
        db: 数据库会话
        template_type: 模板类型
        
    Returns:
        生成的DOCX文件路径
    """
    try:
        # 确保数据库会话中有完整的关联数据
        db.refresh(resume)
        db.refresh(resume.personal_info) if resume.personal_info else None
        for edu in resume.education: db.refresh(edu)
        for exp in resume.work_experience: db.refresh(exp)
        for skill in resume.skills: db.refresh(skill)
        for cert in resume.certificates: db.refresh(cert)
        
        # 创建临时文件
        fd, file_path = tempfile.mkstemp(suffix=".docx")
        os.close(fd)
        
        # 确保模板目录存在
        ensure_templates_dir()
        
        # 选择合适的模板
        template_name = f"{template_type}.html" if os.path.exists(os.path.join(templates_dir, f"{template_type}.html")) else "default.html"
        template = jinja_env.get_template(template_name)
        
        # 渲染HTML内容
        html_content = template.render(resume=resume)
        
        # 使用docx模块创建文档（这里简化处理，实际项目中可以使用python-docx等库）
        # 注意：完整实现需要安装python-docx和pypandoc等依赖
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(html_content)
        
        # 注意：上面的实现只是生成HTML文件并重命名为.docx
        # 实际项目中，应该使用专门的库将HTML转换为真正的DOCX格式
        
        return file_path
        
    except Exception as e:
        print(f"生成DOCX简历失败: {str(e)}")
        # 清理临时文件
        if 'file_path' in locals() and os.path.exists(file_path):
            try:
                os.remove(file_path)
            except:
                pass
        return None

# 初始化：确保模板目录存在
ensure_templates_dir()